package com.zpa.redisstreamlistener.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.Arrays;

@Configuration
public class RedissonConfig {

    @Value("${redisson.alone.host}")
    private String host;
    @Value("${redisson.alone.port}")
    private Integer port;
    @Value("${redisson.alone.password}")
    private String password;
    @Value("${redisson.alone.database}")
    private Integer database;

    /**
     * 单机模式 主要的
     * 多实例情况下 @Bean 没有加 value 的时候 需要加 @Primary 注解
     */
    @Bean
    @Primary
    public RedissonClient redisson(){
        String redisAddress = "redis://" + host + ":" + port;
        // 配置
        Config config = new Config();
        config.useSingleServer().setAddress(redisAddress).setDatabase(database).setPassword(password);
        // 创建RedissonClient对象
        return Redisson.create(config);
    }


    @Value("${redisson.cluster.nodes}")
    private String clusterNodes;
    @Value("${redisson.cluster.password}")
    private String clusterPassword;

    /**
     * 集群模式
     */
    @Bean("redisson2")
    public RedissonClient redisson2(){
        // 配置
        Config config = new Config();
        config.useClusterServers()
                .addNodeAddress(Arrays.stream(clusterNodes.split(","))
                        .map(node -> "redis://" + node)
                        .toArray(String[]::new))
                .setPassword(clusterPassword);

        // 创建RedissonClient对象
        return Redisson.create(config);
    }
}
